package com.situ.ssm.index.controller;

import com.situ.ssm.user.pojo.User;
import com.situ.ssm.user.service.UserService;
import com.situ.ssm.util.ConfigUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * @Project :springssm
 * @Author : yun&bo
 * @Date 2020/12/17 11:40
 * @Version
 */

/**
 * 进首页
 */
@Controller
public class IndexController {
    @Autowired
    private UserService userService;


    @RequestMapping({"/", "index"})
    public ModelAndView goIndex(HttpSession httpSession, ModelAndView modelAndView) {
        User user = (User) httpSession.getAttribute(ConfigUtil.SESSION_LOGIN_USER_NAME);
        if (user != null) {
            modelAndView.setViewName("user/index");
        } else {
            modelAndView.setViewName("login");
        }
        return modelAndView;
    }

    @RequestMapping({"/login"})
    public ModelAndView goLogin(String loginName, HttpSession httpSession, String loginPass, ModelAndView modelAndView) {
        modelAndView.setViewName("login");
        User user = userService.userLogin(loginName, loginPass);
        int flag = LoginStatus(httpSession, user);
        if (user != null && flag == 1) {
            modelAndView.setViewName("user/index");
            return modelAndView;
        }
        return modelAndView;
    }


    @RequestMapping("/exit")
    public String  userExit(HttpSession session){
        System.out.println("退出前"+session.getAttribute(ConfigUtil.SESSION_LOGIN_USER_NAME));
        session.removeAttribute(ConfigUtil.SESSION_LOGIN_USER_NAME);
        System.out.println("推出处session"+session.getAttribute(ConfigUtil.SESSION_LOGIN_USER_NAME));
        return "login";
    }



    /**
     * 登入成功后把用户放入Session
     */
    public int LoginStatus(HttpSession session, User user) {
        session.setAttribute(ConfigUtil.SESSION_LOGIN_USER_NAME, user);
        return 1;
    }


}
